{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convolutional Neural Networks: Step by Step\n",
    "\n",
    "欢迎来到课程4的第一个任务！在这个任务中，你将用numpy实现卷积（CONV）层和池化（POOL）层，包括前向传播和（可选）后向传播。\n",
    "\n",
    "**Notation**:\n",
    "- Superscript $[l]$ denotes an object of the $l^{th}$ layer. \n",
    "    - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.\n",
    "\n",
    "\n",
    "- Superscript $(i)$ denotes an object from the $i^{th}$ example. \n",
    "    - Example: $x^{(i)}$ is the $i^{th}$ training example input.\n",
    "    \n",
    "    \n",
    "- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.\n",
    "    - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer.\n",
    "    \n",
    "    \n",
    "- $n_H$, $n_W$ and $n_C$ denote respectively the height, width and number of channels of a given layer. If you want to reference a specific layer $l$, you can also write $n_H^{[l]}$, $n_W^{[l]}$, $n_C^{[l]}$. \n",
    "- $n_{H_{prev}}$, $n_{W_{prev}}$ and $n_{C_{prev}}$ denote respectively the height, width and number of channels of the previous layer. If referencing a specific layer $l$, this could also be denoted $n_H^{[l-1]}$, $n_W^{[l-1]}$, $n_C^{[l-1]}$. \n",
    "\n",
    "我们假设你已经熟悉了numpy并完成了之前的专业课程。让我们开始吧！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 - Packages\n",
    "\n",
    "导入本次任务需要的包 \n",
    "- [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.\n",
    "- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.\n",
    "- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import h5py\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "%matplotlib inline\n",
    "plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\n",
    "plt.rcParams['image.interpolation'] = 'nearest'\n",
    "plt.rcParams['image.cmap'] = 'gray'\n",
    "\n",
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "np.random.seed(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 - Outline of the Assignment\n",
    "\n",
    "你即将实现一个卷积神经网络！网络的每个功能模块都有详细的说明，会引导你完成相关步骤：\n",
    "\n",
    "- Convolution functions, including:\n",
    "    - Zero Padding 零填充\n",
    "    - Convolve window 卷积窗口\n",
    "    - Convolution forward \n",
    "    - Convolution backward (optional)\n",
    "- Pooling functions, including:\n",
    "    - Pooling forward\n",
    "    - Create mask \n",
    "    - Distribute value\n",
    "    - Pooling backward (optional)\n",
    "    \n",
    "本次任务会要求你用 python 来实现每个函数. 下次任务则用 TensorFlow 中等价的函数构造如下模型:\n",
    "\n",
    "<img src=\"images/model.png\" style=\"width:800px;height:300px;\">\n",
    "\n",
    "**请注意**，对于每个前向传播，都有相应的反向传播。因此，每一步前向传播，都会存储一些参数在缓存中。这些参数用于计算反向传播中的梯度。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 - 卷积神经网络\n",
    "\n",
    "尽管编程框架使得卷积操作易于实现，但它仍然是深度学习中最难理解的概念之一。卷积层将输入转换为不同尺寸的输出，如下所示。\n",
    "\n",
    "<img src=\"images/conv_nn.png\" style=\"width:350px;height:200px;\">\n",
    "\n",
    "在这一部分，您将实现卷积层的每一个细节。你首先要实现两个辅助函数：一个用于零填充，另一个用于卷积计算。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 - Zero-Padding\n",
    "\n",
    "Zero-padding 指在图像的边缘填充系列零点:\n",
    "\n",
    "<img src=\"images/PAD.png\" style=\"width:600px;height:400px;\">\n",
    "<caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'>  : **Zero-Padding**<br> Image (3 channels, RGB) with a padding of 2. </center></caption>\n",
    "\n",
    "Zero-padding 零填充的主要好处如下：\n",
    "\n",
    "- 它允许你在不缩小宽度和高度的同时使用CONV层. 这对构建更深层次的网络非常重要, 否则网络越深，宽度/高度越小. 一个重要的特殊案例是 \"same\" convolution, 它在经历一层卷积后宽度/高度维持不变. \n",
    "\n",
    "- 它会在图像的边界保留更多的信息. 如果没有填充，下一层的极少数值会受到边缘像素的影响。\n",
    "\n",
    "**Exercise**: 使用  [Use np.pad](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html) 实现函数 zero_pad , 将一批样本X中的所有图像填充为零. Note if you want to pad the array \"a\" of shape $(5,5,5,5,5)$ with `pad = 1` for the 2nd dimension, `pad = 3` for the 4th dimension and `pad = 0` for the rest, you would do:\n",
    "```python\n",
    "a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..))\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: zero_pad\n",
    "\n",
    "def zero_pad(X, pad):\n",
    "    \"\"\"\n",
    "    Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, \n",
    "    as illustrated in Figure 1.\n",
    "    \n",
    "    Argument:\n",
    "    X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images\n",
    "    pad -- integer, amount of padding around each image on vertical and horizontal dimensions\n",
    "    \n",
    "    Returns:\n",
    "    X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ### (≈ 1 line)\n",
    "    X_pad = None\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    return X_pad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "x = np.random.randn(4, 3, 3, 2)\n",
    "x_pad = zero_pad(x, 2)\n",
    "print (\"x.shape =\", x.shape)\n",
    "print (\"x_pad.shape =\", x_pad.shape)\n",
    "print (\"x[1,1] =\", x[1,1])\n",
    "print (\"x_pad[1,1] =\", x_pad[1,1])\n",
    "\n",
    "fig, axarr = plt.subplots(1, 2)\n",
    "axarr[0].set_title('x')\n",
    "axarr[0].imshow(x[0,:,:,0])\n",
    "axarr[1].set_title('x_pad')\n",
    "axarr[1].imshow(x_pad[0,:,:,0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Expected Output**:\n",
    "\n",
    "<table>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **x.shape**:\n",
    "        </td>\n",
    "        <td>\n",
    "           (4, 3, 3, 2)\n",
    "        </td>\n",
    "    </tr>\n",
    "        <tr>\n",
    "        <td>\n",
    "            **x_pad.shape**:\n",
    "        </td>\n",
    "        <td>\n",
    "           (4, 7, 7, 2)\n",
    "        </td>\n",
    "    </tr>\n",
    "        <tr>\n",
    "        <td>\n",
    "            **x[1,1]**:\n",
    "        </td>\n",
    "        <td>\n",
    "           [[ 0.90085595 -0.68372786]\n",
    " [-0.12289023 -0.93576943]\n",
    " [-0.26788808  0.53035547]]\n",
    "        </td>\n",
    "    </tr>\n",
    "        <tr>\n",
    "        <td>\n",
    "            **x_pad[1,1]**:\n",
    "        </td>\n",
    "        <td>\n",
    "           [[ 0.  0.]\n",
    " [ 0.  0.]\n",
    " [ 0.  0.]\n",
    " [ 0.  0.]\n",
    " [ 0.  0.]\n",
    " [ 0.  0.]\n",
    " [ 0.  0.]]\n",
    "        </td>\n",
    "    </tr>\n",
    "\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 - Single step of convolution \n",
    "\n",
    "In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which: \n",
    "\n",
    "- Takes an input volume \n",
    "- Applies a filter at every position of the input\n",
    "- Outputs another volume (usually of different size)\n",
    "\n",
    "<img src=\"images/Convolution_schematic.gif\" style=\"width:500px;height:300px;\">\n",
    "<caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'>  : **Convolution operation**<br> with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide) </center></caption>\n",
    "\n",
    "在计算机视觉应用中，左侧矩阵中的每个值对应于单个像素值, and we convolve a 3x3 filter with the image by multiplying its values element-wise with the original matrix, then summing them up. In this first step of the exercise, you will implement a single step of convolution, corresponding to applying a filter to just one of the positions to get a single real-valued output. \n",
    "\n",
    "Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation(在这个任务的后面，你将把这个函数应用到输入的多个位置来实现完整的卷积操作).\n",
    "\n",
    "**Exercise**: Implement conv_single_step(). [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: conv_single_step\n",
    "\n",
    "def conv_single_step(a_slice_prev, W, b):\n",
    "    \"\"\"\n",
    "    Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation \n",
    "    of the previous layer.\n",
    "    \n",
    "    Arguments:\n",
    "    a_slice_prev -- slice of input data of shape (f, f, n_C_prev)\n",
    "    W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev)\n",
    "    b -- Bias parameters contained in a window - matrix of shape (1, 1, 1)\n",
    "    \n",
    "    Returns:\n",
    "    Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data\n",
    "    \"\"\"\n",
    "\n",
    "    ### START CODE HERE ### (≈ 2 lines of code)\n",
    "    # Element-wise product between a_slice and W. Add bias.\n",
    "    s = None\n",
    "    # Sum over all entries of the volume s\n",
    "    Z = None\n",
    "    ### END CODE HERE ###\n",
    "\n",
    "    return Z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "a_slice_prev = np.random.randn(4, 4, 3)\n",
    "W = np.random.randn(4, 4, 3)\n",
    "b = np.random.randn(1, 1, 1)\n",
    "\n",
    "Z = conv_single_step(a_slice_prev, W, b)\n",
    "print(\"Z =\", Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Expected Output**:\n",
    "<table>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **Z**\n",
    "        </td>\n",
    "        <td>\n",
    "            -23.1602122025\n",
    "        </td>\n",
    "    </tr>\n",
    "\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### 3.3 - Convolutional Neural Networks - Forward pass\n",
    "\n",
    "在正向传递中，您将对输入采用多种过滤器进行卷积。每个“卷积”输出一个二维矩阵。最后叠加二维矩阵获得 a 3D volume：\n",
    "\n",
    "\n",
    "\n",
    "<center>\n",
    "<video width=\"620\" height=\"440\" src=\"images/conv_kiank.mp4\" type=\"video/mp4\" controls>\n",
    "</video>\n",
    "</center>\n",
    "\n",
    "**Exercise**: Implement the function below to convolve the filters W on an input activation A_prev. This function takes as input A_prev, the activations output by the previous layer (for a batch of m inputs), F filters/weights denoted by W, and a bias vector denoted by b, where each filter has its own (single) bias. Finally you also have access to the hyperparameters dictionary which contains the stride and the padding. \n",
    "\n",
    "**Hint**: \n",
    "1. 要获取矩阵“a_prev”（形状（5,5,3））左上角 2x2 的切片，你需要:\n",
    "```python\n",
    "a_slice_prev = a_prev[0:2,0:2,:]\n",
    "```\n",
    "This will be useful when you will define `a_slice_prev` below, using the `start/end` indexes you will define.\n",
    "2. To define a_slice you will need to first define its corners `vert_start`, `vert_end`, `horiz_start` and `horiz_end`. This figure may be helpful for you to find how each of the corner can be defined using h, w, f and s in the code below.\n",
    "\n",
    "<img src=\"images/vert_horiz_kiank.png\" style=\"width:400px;height:300px;\">\n",
    "<caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'>  : **Definition of a slice using vertical and horizontal start/end (with a 2x2 filter)** <br> This figure shows only a single channel.  </center></caption>\n",
    "\n",
    "\n",
    "**Reminder**:\n",
    "卷积操作输入输出的公式是:\n",
    "$$ n_H = \\lfloor \\frac{n_{H_{prev}} - f + 2 \\times pad}{stride} \\rfloor +1 $$\n",
    "$$ n_W = \\lfloor \\frac{n_{W_{prev}} - f + 2 \\times pad}{stride} \\rfloor +1 $$\n",
    "$$ n_C = \\text{number of filters used in the convolution}$$\n",
    "\n",
    "在这个练习中，我们不用矢量化数据，用for循环去实现所有的东西。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: conv_forward\n",
    "\n",
    "def conv_forward(A_prev, W, b, hparameters):\n",
    "    \"\"\"\n",
    "    Implements the forward propagation for a convolution function\n",
    "    \n",
    "    Arguments:\n",
    "    A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)\n",
    "    W -- Weights, numpy array of shape (f, f, n_C_prev, n_C)\n",
    "    b -- Biases, numpy array of shape (1, 1, 1, n_C)\n",
    "    hparameters -- python dictionary containing \"stride\" and \"pad\"\n",
    "        \n",
    "    Returns:\n",
    "    Z -- conv output, numpy array of shape (m, n_H, n_W, n_C)\n",
    "    cache -- cache of values needed for the conv_backward() function\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ###\n",
    "    # Retrieve dimensions from A_prev's shape (≈1 line)  \n",
    "    (m, n_H_prev, n_W_prev, n_C_prev) = None\n",
    "    \n",
    "    # Retrieve dimensions from W's shape (≈1 line)\n",
    "    (f, f, n_C_prev, n_C) = None\n",
    "    \n",
    "    # Retrieve information from \"hparameters\" (≈2 lines)\n",
    "    stride = None\n",
    "    pad = None\n",
    "    \n",
    "    # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines)\n",
    "    n_H = None\n",
    "    n_W = None\n",
    "    \n",
    "    # Initialize the output volume Z with zeros. (≈1 line)\n",
    "    Z = None\n",
    "    \n",
    "    # Create A_prev_pad by padding A_prev\n",
    "    A_prev_pad = None\n",
    "    \n",
    "    for i in range(None):                               # loop over the batch of training examples\n",
    "        a_prev_pad = None                               # Select ith training example's padded activation\n",
    "        for h in range(None):                           # loop over vertical axis of the output volume\n",
    "            for w in range(None):                       # loop over horizontal axis of the output volume\n",
    "                for c in range(None):                   # loop over channels (= #filters) of the output volume\n",
    "                    \n",
    "                    # Find the corners of the current \"slice\" (≈4 lines)\n",
    "                    vert_start = None\n",
    "                    vert_end = None\n",
    "                    horiz_start = None\n",
    "                    horiz_end = None\n",
    "                    \n",
    "                    # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line)\n",
    "                    a_slice_prev = None\n",
    "                    \n",
    "                    # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line)\n",
    "                    Z[i, h, w, c] = None\n",
    "                                        \n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    # Making sure your output shape is correct\n",
    "    assert(Z.shape == (m, n_H, n_W, n_C))\n",
    "    \n",
    "    # Save information in \"cache\" for the backprop\n",
    "    cache = (A_prev, W, b, hparameters)\n",
    "    \n",
    "    return Z, cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "A_prev = np.random.randn(10,4,4,3)\n",
    "W = np.random.randn(2,2,3,8)\n",
    "b = np.random.randn(1,1,1,8)\n",
    "hparameters = {\"pad\" : 2,\n",
    "               \"stride\": 1}\n",
    "\n",
    "Z, cache_conv = conv_forward(A_prev, W, b, hparameters)\n",
    "print(\"Z's mean =\", np.mean(Z))\n",
    "print(\"cache_conv[0][1][2][3] =\", cache_conv[0][1][2][3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Expected Output**:\n",
    "\n",
    "<table>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **Z's mean**\n",
    "        </td>\n",
    "        <td>\n",
    "            0.155859324889\n",
    "        </td>\n",
    "    </tr>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **cache_conv[0][1][2][3]**\n",
    "        </td>\n",
    "        <td>\n",
    "            [-0.20075807  0.18656139  0.41005165]\n",
    "        </td>\n",
    "    </tr>\n",
    "\n",
    "</table>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后，CONV层应该还包含一个激活功能，这种情况下，我们可以添加以下代码：\n",
    "\n",
    "```python\n",
    "# Convolve the window to get back one output neuron\n",
    "Z[i, h, w, c] = ...\n",
    "# Apply activation\n",
    "A[i, h, w, c] = activation(Z[i, h, w, c])\n",
    "```\n",
    "\n",
    "你不需要在这里做。 \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 - Pooling layer \n",
    "\n",
    "池化（POOL）层会降低输入的高度和宽度。它有助于减少计算量, as well as helps make feature detectors more invariant to its position in the input. 有两种类型的池化: \n",
    "\n",
    "- Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output.\n",
    "\n",
    "- Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output.\n",
    "\n",
    "<table>\n",
    "<td>\n",
    "<img src=\"images/max_pool1.png\" style=\"width:500px;height:300px;\">\n",
    "<td>\n",
    "\n",
    "<td>\n",
    "<img src=\"images/a_pool.png\" style=\"width:500px;height:300px;\">\n",
    "<td>\n",
    "</table>\n",
    "\n",
    "反向传播，池化层没有需要训练的参数. 但是，它们有超参，例如窗口大小 $f$. This specifies the height and width of the fxf window you would compute a max or average over. \n",
    "\n",
    "### 4.1 - Forward Pooling\n",
    "现在，您将在同一个函数中实现MAX-POOL和AVG-POOL。\n",
    "\n",
    "**Exercise**: 按照下面的注释中的提示实现池化层的正向传递。\n",
    "\n",
    "**Reminder**:\n",
    "由于没有填充, the formulas binding the output shape of the pooling to the input shape is:\n",
    "$$ n_H = \\lfloor \\frac{n_{H_{prev}} - f}{stride} \\rfloor +1 $$\n",
    "$$ n_W = \\lfloor \\frac{n_{W_{prev}} - f}{stride} \\rfloor +1 $$\n",
    "$$ n_C = n_{C_{prev}}$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: pool_forward\n",
    "\n",
    "def pool_forward(A_prev, hparameters, mode = \"max\"):\n",
    "    \"\"\"\n",
    "    Implements the forward pass of the pooling layer\n",
    "    \n",
    "    Arguments:\n",
    "    A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)\n",
    "    hparameters -- python dictionary containing \"f\" and \"stride\"\n",
    "    mode -- the pooling mode you would like to use, defined as a string (\"max\" or \"average\")\n",
    "    \n",
    "    Returns:\n",
    "    A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C)\n",
    "    cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters \n",
    "    \"\"\"\n",
    "    \n",
    "    # Retrieve dimensions from the input shape\n",
    "    (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape\n",
    "    \n",
    "    # Retrieve hyperparameters from \"hparameters\"\n",
    "    f = hparameters[\"f\"]\n",
    "    stride = hparameters[\"stride\"]\n",
    "    \n",
    "    # Define the dimensions of the output\n",
    "    n_H = int(1 + (n_H_prev - f) / stride)\n",
    "    n_W = int(1 + (n_W_prev - f) / stride)\n",
    "    n_C = n_C_prev\n",
    "    \n",
    "    # Initialize output matrix A\n",
    "    A = np.zeros((m, n_H, n_W, n_C))              \n",
    "    \n",
    "    ### START CODE HERE ###\n",
    "    for i in range(None):                         # loop over the training examples\n",
    "        for h in range(None):                     # loop on the vertical axis of the output volume\n",
    "            for w in range(None):                 # loop on the horizontal axis of the output volume\n",
    "                for c in range (None):            # loop over the channels of the output volume\n",
    "                    \n",
    "                    # Find the corners of the current \"slice\" (≈4 lines)\n",
    "                    vert_start = None\n",
    "                    vert_end = None\n",
    "                    horiz_start = None\n",
    "                    horiz_end = None\n",
    "                    \n",
    "                    # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line)\n",
    "                    a_prev_slice = None\n",
    "                    \n",
    "                    # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean.\n",
    "                    if mode == \"max\":\n",
    "                        A[i, h, w, c] = None\n",
    "                    elif mode == \"average\":\n",
    "                        A[i, h, w, c] = None\n",
    "    \n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    # Store the input and hparameters in \"cache\" for pool_backward()\n",
    "    cache = (A_prev, hparameters)\n",
    "    \n",
    "    # Making sure your output shape is correct\n",
    "    assert(A.shape == (m, n_H, n_W, n_C))\n",
    "    \n",
    "    return A, cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "A_prev = np.random.randn(2, 4, 4, 3)\n",
    "hparameters = {\"stride\" : 1, \"f\": 4}\n",
    "\n",
    "A, cache = pool_forward(A_prev, hparameters)\n",
    "print(\"mode = max\")\n",
    "print(\"A =\", A)\n",
    "print()\n",
    "A, cache = pool_forward(A_prev, hparameters, mode = \"average\")\n",
    "print(\"mode = average\")\n",
    "print(\"A =\", A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Expected Output:**\n",
    "<table>\n",
    "\n",
    "    <tr>\n",
    "    <td>\n",
    "    A  =\n",
    "    </td>\n",
    "        <td>\n",
    "         [[[[ 1.74481176  1.6924546   2.10025514]]] <br/>\n",
    "\n",
    "\n",
    " [[[ 1.19891788  1.51981682  2.18557541]]]]\n",
    "\n",
    "        </td>\n",
    "    </tr>\n",
    "    <tr>\n",
    "    <td>\n",
    "    A  =\n",
    "    </td>\n",
    "        <td>\n",
    "         [[[[-0.09498456  0.11180064 -0.14263511]]] <br/>\n",
    "\n",
    "\n",
    " [[[-0.09525108  0.28325018  0.33035185]]]]\n",
    "\n",
    "        </td>\n",
    "    </tr>\n",
    "\n",
    "</table>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "恭喜！您现在已经实现了卷积神经网络所有层的前向传递。\n",
    "\n",
    "本次任务剩下的部分是可选的，不会参与评分。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 - Backpropagation in convolutional neural networks (OPTIONAL / UNGRADED)\n",
    "\n",
    "在当前的深度学习框架中，只需要实现正向传递，框架自身会关注反向传递，所以大多数深度学习工程师不需要关注反向传递的细节。卷积网络的反向传递很复杂。如果你愿意的话，你可以通过本次笔记的后半部分来了解卷积网络中的反向链路是什么样的。\n",
    "\n",
    "在之前的课程中，您实现了一个简单（完全连接）的神经网络，您通过反向传播计算损失的倒数来更新参数。同样，在卷积神经网络中，您也可以根据损失计算导数来更新参数。反向传播的公式不太重要，我们并没有在讲座中推导它们，但我们在下面会对它进行简要地介绍。\n",
    "\n",
    "### 5.1 - Convolutional layer backward pass \n",
    "\n",
    "我们首先实现一个CONV层的反向传递。\n",
    "\n",
    "#### 5.1.1 - Computing dA:\n",
    "This is the formula for computing $dA$ with respect to the cost for a certain filter $W_c$ and a given training example:\n",
    "\n",
    "$$ dA += \\sum _{h=0} ^{n_H} \\sum_{w=0} ^{n_W} W_c \\times dZ_{hw} \\tag{1}$$\n",
    "\n",
    "Where $W_c$ is a filter and $dZ_{hw}$ is a scalar corresponding to the gradient of the cost with respect to the output of the conv layer Z at the hth row and wth column (corresponding to the dot product taken at the ith stride left and jth stride down). Note that at each time, we multiply the the same filter $W_c$ by a different dZ when updating dA. We do so mainly because when computing the forward propagation, each filter is dotted and summed by a different a_slice. Therefore when computing the backprop for dA, we are just adding the gradients of all the a_slices. \n",
    "\n",
    "In code, inside the appropriate for-loops, this formula translates into:\n",
    "```python\n",
    "da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]\n",
    "```\n",
    "\n",
    "#### 5.1.2 - Computing dW:\n",
    "This is the formula for computing $dW_c$ ($dW_c$ is the derivative of one filter) with respect to the loss:\n",
    "\n",
    "$$ dW_c  += \\sum _{h=0} ^{n_H} \\sum_{w=0} ^ {n_W} a_{slice} \\times dZ_{hw}  \\tag{2}$$\n",
    "\n",
    "Where $a_{slice}$ corresponds to the slice which was used to generate the acitivation $Z_{ij}$. Hence, this ends up giving us the gradient for $W$ with respect to that slice. Since it is the same $W$, we will just add up all such gradients to get $dW$. \n",
    "\n",
    "In code, inside the appropriate for-loops, this formula translates into:\n",
    "```python\n",
    "dW[:,:,:,c] += a_slice * dZ[i, h, w, c]\n",
    "```\n",
    "\n",
    "#### 5.1.3 - Computing db:\n",
    "\n",
    "This is the formula for computing $db$ with respect to the cost for a certain filter $W_c$:\n",
    "\n",
    "$$ db = \\sum_h \\sum_w dZ_{hw} \\tag{3}$$\n",
    "\n",
    "As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost. \n",
    "\n",
    "In code, inside the appropriate for-loops, this formula translates into:\n",
    "```python\n",
    "db[:,:,:,c] += dZ[i, h, w, c]\n",
    "```\n",
    "\n",
    "**Exercise**: Implement the `conv_backward` function below. You should sum over all the training examples, filters, heights, and widths. You should then compute the derivatives using formulas 1, 2 and 3 above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def conv_backward(dZ, cache):\n",
    "    \"\"\"\n",
    "    Implement the backward propagation for a convolution function\n",
    "    \n",
    "    Arguments:\n",
    "    dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C)\n",
    "    cache -- cache of values needed for the conv_backward(), output of conv_forward()\n",
    "    \n",
    "    Returns:\n",
    "    dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev),\n",
    "               numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)\n",
    "    dW -- gradient of the cost with respect to the weights of the conv layer (W)\n",
    "          numpy array of shape (f, f, n_C_prev, n_C)\n",
    "    db -- gradient of the cost with respect to the biases of the conv layer (b)\n",
    "          numpy array of shape (1, 1, 1, n_C)\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ###\n",
    "    # Retrieve information from \"cache\"\n",
    "    (A_prev, W, b, hparameters) = None\n",
    "    \n",
    "    # Retrieve dimensions from A_prev's shape\n",
    "    (m, n_H_prev, n_W_prev, n_C_prev) = None\n",
    "    \n",
    "    # Retrieve dimensions from W's shape\n",
    "    (f, f, n_C_prev, n_C) = None\n",
    "    \n",
    "    # Retrieve information from \"hparameters\"\n",
    "    stride = None\n",
    "    pad = None\n",
    "    \n",
    "    # Retrieve dimensions from dZ's shape\n",
    "    (m, n_H, n_W, n_C) = None\n",
    "    \n",
    "    # Initialize dA_prev, dW, db with the correct shapes\n",
    "    dA_prev = None                           \n",
    "    dW = None\n",
    "    db = None\n",
    "\n",
    "    # Pad A_prev and dA_prev\n",
    "    A_prev_pad = None\n",
    "    dA_prev_pad = None\n",
    "    \n",
    "    for i in range(None):                       # loop over the training examples\n",
    "        \n",
    "        # select ith training example from A_prev_pad and dA_prev_pad\n",
    "        a_prev_pad = None\n",
    "        da_prev_pad = None\n",
    "        \n",
    "        for h in range(None):                   # loop over vertical axis of the output volume\n",
    "            for w in range(None):               # loop over horizontal axis of the output volume\n",
    "                for c in range(None):           # loop over the channels of the output volume\n",
    "                    \n",
    "                    # Find the corners of the current \"slice\"\n",
    "                    vert_start = None\n",
    "                    vert_end = None\n",
    "                    horiz_start = None\n",
    "                    horiz_end = None\n",
    "                    \n",
    "                    # Use the corners to define the slice from a_prev_pad\n",
    "                    a_slice = None\n",
    "\n",
    "                    # Update gradients for the window and the filter's parameters using the code formulas given above\n",
    "                    da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += None\n",
    "                    dW[:,:,:,c] += None\n",
    "                    db[:,:,:,c] += None\n",
    "                    \n",
    "        # Set the ith training example's dA_prev to the unpaded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :])\n",
    "        dA_prev[i, :, :, :] = None\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    # Making sure your output shape is correct\n",
    "    assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev))\n",
    "    \n",
    "    return dA_prev, dW, db"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "dA, dW, db = conv_backward(Z, cache_conv)\n",
    "print(\"dA_mean =\", np.mean(dA))\n",
    "print(\"dW_mean =\", np.mean(dW))\n",
    "print(\"db_mean =\", np.mean(db))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "** Expected Output: **\n",
    "<table>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **dA_mean**\n",
    "        </td>\n",
    "        <td>\n",
    "            9.60899067587\n",
    "        </td>\n",
    "    </tr>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **dW_mean**\n",
    "        </td>\n",
    "        <td>\n",
    "            10.5817412755\n",
    "        </td>\n",
    "    </tr>\n",
    "    <tr>\n",
    "        <td>\n",
    "            **db_mean**\n",
    "        </td>\n",
    "        <td>\n",
    "            76.3710691956\n",
    "        </td>\n",
    "    </tr>\n",
    "\n",
    "</table>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.2 Pooling layer - backward pass\n",
    "\n",
    "Next, let's implement the backward pass for the pooling layer, starting with the MAX-POOL layer. Even though a pooling layer has no parameters for backprop to update, you still need to backpropagation the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer. \n",
    "\n",
    "### 5.2.1 Max pooling - backward pass  \n",
    "\n",
    "Before jumping into the backpropagation of the pooling layer, you are going to build a helper function called `create_mask_from_window()` which does the following: \n",
    "\n",
    "$$ X = \\begin{bmatrix}\n",
    "1 && 3 \\\\\n",
    "4 && 2\n",
    "\\end{bmatrix} \\quad \\rightarrow  \\quad M =\\begin{bmatrix}\n",
    "0 && 0 \\\\\n",
    "1 && 0\n",
    "\\end{bmatrix}\\tag{4}$$\n",
    "\n",
    "As you can see, this function creates a \"mask\" matrix which keeps track of where the maximum of the matrix is. True (1) indicates the position of the maximum in X, the other entries are False (0). You'll see later that the backward pass for average pooling will be similar to this but using a different mask.  \n",
    "\n",
    "**Exercise**: Implement `create_mask_from_window()`. This function will be helpful for pooling backward. \n",
    "Hints:\n",
    "- [np.max()]() may be helpful. It computes the maximum of an array.\n",
    "- If you have a matrix X and a scalar x: `A = (X == x)` will return a matrix A of the same size as X such that:\n",
    "```\n",
    "A[i,j] = True if X[i,j] = x\n",
    "A[i,j] = False if X[i,j] != x\n",
    "```\n",
    "- Here, you don't need to consider cases where there are several maxima in a matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def create_mask_from_window(x):\n",
    "    \"\"\"\n",
    "    Creates a mask from an input matrix x, to identify the max entry of x.\n",
    "    \n",
    "    Arguments:\n",
    "    x -- Array of shape (f, f)\n",
    "    \n",
    "    Returns:\n",
    "    mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x.\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ### (≈1 line)\n",
    "    mask = None\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    return mask"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "x = np.random.randn(2,3)\n",
    "mask = create_mask_from_window(x)\n",
    "print('x = ', x)\n",
    "print(\"mask = \", mask)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "**Expected Output:** \n",
    "\n",
    "<table> \n",
    "<tr> \n",
    "<td>\n",
    "\n",
    "**x =**\n",
    "</td>\n",
    "\n",
    "<td>\n",
    "\n",
    "[[ 1.62434536 -0.61175641 -0.52817175] <br>\n",
    " [-1.07296862  0.86540763 -2.3015387 ]]\n",
    "\n",
    "  </td>\n",
    "</tr>\n",
    "\n",
    "<tr> \n",
    "<td>\n",
    "**mask =**\n",
    "</td>\n",
    "<td>\n",
    "[[ True False False] <br>\n",
    " [False False False]]\n",
    "</td>\n",
    "</tr>\n",
    "\n",
    "\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why do we keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is computing gradients with respect to the cost, so anything that influences the ultimate cost should have a non-zero gradient. So, backprop will \"propagate\" the gradient back to this particular input value that had influenced the cost. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.2.2 - Average pooling - backward pass \n",
    "\n",
    "In max pooling, for each input window, all the \"influence\" on the output came from a single input value--the max. In average pooling, every element of the input window has equal influence on the output. So to implement backprop, you will now implement a helper function that reflects this.\n",
    "\n",
    "For example if we did average pooling in the forward pass using a 2x2 filter, then the mask you'll use for the backward pass will look like: \n",
    "$$ dZ = 1 \\quad \\rightarrow  \\quad dZ =\\begin{bmatrix}\n",
    "1/4 && 1/4 \\\\\n",
    "1/4 && 1/4\n",
    "\\end{bmatrix}\\tag{5}$$\n",
    "\n",
    "This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average. \n",
    "\n",
    "**Exercise**: Implement the function below to equally distribute a value dz through a matrix of dimension shape. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ones.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def distribute_value(dz, shape):\n",
    "    \"\"\"\n",
    "    Distributes the input value in the matrix of dimension shape\n",
    "    \n",
    "    Arguments:\n",
    "    dz -- input scalar\n",
    "    shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz\n",
    "    \n",
    "    Returns:\n",
    "    a -- Array of size (n_H, n_W) for which we distributed the value of dz\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ###\n",
    "    # Retrieve dimensions from shape (≈1 line)\n",
    "    (n_H, n_W) = None\n",
    "    \n",
    "    # Compute the value to distribute on the matrix (≈1 line)\n",
    "    average = None\n",
    "    \n",
    "    # Create a matrix where every entry is the \"average\" value (≈1 line)\n",
    "    a = None\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    return a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "a = distribute_value(2, (2,2))\n",
    "print('distributed value =', a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Expected Output**: \n",
    "\n",
    "<table> \n",
    "<tr> \n",
    "<td>\n",
    "distributed_value =\n",
    "</td>\n",
    "<td>\n",
    "[[ 0.5  0.5]\n",
    "<br\\> \n",
    "[ 0.5  0.5]]\n",
    "</td>\n",
    "</tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.2.3 Putting it together: Pooling backward \n",
    "\n",
    "You now have everything you need to compute backward propagation on a pooling layer.\n",
    "\n",
    "**Exercise**: Implement the `pool_backward` function in both modes (`\"max\"` and `\"average\"`). You will once again use 4 for-loops (iterating over training examples, height, width, and channels). You should use an `if/elif` statement to see if the mode is equal to `'max'` or `'average'`. If it is equal to 'average' you should use the `distribute_value()` function you implemented above to create a matrix of the same shape as `a_slice`. Otherwise, the mode is equal to '`max`', and you will create a mask with `create_mask_from_window()` and multiply it by the corresponding value of dZ."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def pool_backward(dA, cache, mode = \"max\"):\n",
    "    \"\"\"\n",
    "    Implements the backward pass of the pooling layer\n",
    "    \n",
    "    Arguments:\n",
    "    dA -- gradient of cost with respect to the output of the pooling layer, same shape as A\n",
    "    cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters \n",
    "    mode -- the pooling mode you would like to use, defined as a string (\"max\" or \"average\")\n",
    "    \n",
    "    Returns:\n",
    "    dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ###\n",
    "    \n",
    "    # Retrieve information from cache (≈1 line)\n",
    "    (A_prev, hparameters) = None\n",
    "    \n",
    "    # Retrieve hyperparameters from \"hparameters\" (≈2 lines)\n",
    "    stride = None\n",
    "    f = None\n",
    "    \n",
    "    # Retrieve dimensions from A_prev's shape and dA's shape (≈2 lines)\n",
    "    m, n_H_prev, n_W_prev, n_C_prev = None\n",
    "    m, n_H, n_W, n_C = None\n",
    "    \n",
    "    # Initialize dA_prev with zeros (≈1 line)\n",
    "    dA_prev = None\n",
    "    \n",
    "    for i in range(None):                       # loop over the training examples\n",
    "        \n",
    "        # select training example from A_prev (≈1 line)\n",
    "        a_prev = None\n",
    "        \n",
    "        for h in range(None):                   # loop on the vertical axis\n",
    "            for w in range(None):               # loop on the horizontal axis\n",
    "                for c in range(None):           # loop over the channels (depth)\n",
    "                    \n",
    "                    # Find the corners of the current \"slice\" (≈4 lines)\n",
    "                    vert_start = None\n",
    "                    vert_end = None\n",
    "                    horiz_start = None\n",
    "                    horiz_end = None\n",
    "                    \n",
    "                    # Compute the backward propagation in both modes.\n",
    "                    if mode == \"max\":\n",
    "                        \n",
    "                        # Use the corners and \"c\" to define the current slice from a_prev (≈1 line)\n",
    "                        a_prev_slice = None\n",
    "                        # Create the mask from a_prev_slice (≈1 line)\n",
    "                        mask = None\n",
    "                        # Set dA_prev to be dA_prev + (the mask multiplied by the correct entry of dA) (≈1 line)\n",
    "                        dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += None\n",
    "                        \n",
    "                    elif mode == \"average\":\n",
    "                        \n",
    "                        # Get the value a from dA (≈1 line)\n",
    "                        da = None\n",
    "                        # Define the shape of the filter as fxf (≈1 line)\n",
    "                        shape = None\n",
    "                        # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da. (≈1 line)\n",
    "                        dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += None\n",
    "                        \n",
    "    ### END CODE ###\n",
    "    \n",
    "    # Making sure your output shape is correct\n",
    "    assert(dA_prev.shape == A_prev.shape)\n",
    "    \n",
    "    return dA_prev"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "A_prev = np.random.randn(5, 5, 3, 2)\n",
    "hparameters = {\"stride\" : 1, \"f\": 2}\n",
    "A, cache = pool_forward(A_prev, hparameters)\n",
    "dA = np.random.randn(5, 4, 2, 2)\n",
    "\n",
    "dA_prev = pool_backward(dA, cache, mode = \"max\")\n",
    "print(\"mode = max\")\n",
    "print('mean of dA = ', np.mean(dA))\n",
    "print('dA_prev[1,1] = ', dA_prev[1,1])  \n",
    "print()\n",
    "dA_prev = pool_backward(dA, cache, mode = \"average\")\n",
    "print(\"mode = average\")\n",
    "print('mean of dA = ', np.mean(dA))\n",
    "print('dA_prev[1,1] = ', dA_prev[1,1]) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Expected Output**: \n",
    "\n",
    "mode = max:\n",
    "<table> \n",
    "<tr> \n",
    "<td>\n",
    "\n",
    "**mean of dA =**\n",
    "</td>\n",
    "\n",
    "<td>\n",
    "\n",
    "0.145713902729\n",
    "\n",
    "  </td>\n",
    "</tr>\n",
    "\n",
    "<tr> \n",
    "<td>\n",
    "**dA_prev[1,1] =** \n",
    "</td>\n",
    "<td>\n",
    "[[ 0.          0.        ] <br>\n",
    " [ 5.05844394 -1.68282702] <br>\n",
    " [ 0.          0.        ]]\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "mode = average\n",
    "<table> \n",
    "<tr> \n",
    "<td>\n",
    "\n",
    "**mean of dA =**\n",
    "</td>\n",
    "\n",
    "<td>\n",
    "\n",
    "0.145713902729\n",
    "\n",
    "  </td>\n",
    "</tr>\n",
    "\n",
    "<tr> \n",
    "<td>\n",
    "**dA_prev[1,1] =** \n",
    "</td>\n",
    "<td>\n",
    "[[ 0.08485462  0.2787552 ] <br>\n",
    " [ 1.26461098 -0.25749373] <br>\n",
    " [ 1.17975636 -0.53624893]]\n",
    "</td>\n",
    "</tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Congratulations !\n",
    "\n",
    "Congratulation on completing this assignment. You now understand how convolutional neural networks work. You have implemented all the building blocks of a neural network. In the next assignment you will implement a ConvNet using TensorFlow."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "coursera": {
   "course_slug": "convolutional-neural-networks",
   "graded_item_id": "qO8ng",
   "launcher_item_id": "7XDi8"
  },
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
